#include "stdafx.h"
#include "CWinReader.h"
#include "IPALDebuggingServices.h"
#include <xmllite.h>

CWinReader::CWinReader(void)
{
	this->m_cRef = 1;
	this->m_hLibrary = NULL;
	this->m_pReader = NULL;
	this->m_pStream = NULL;
}


CWinReader::~CWinReader(void)
{
	if ( this->m_pStream )
	{
		this->m_pStream->Release();
		this->m_pStream = NULL;
	}
	if ( this->m_pReader )
	{
		this->m_pReader->Release();
		this->m_pReader = NULL;
	}
}

XUINT32 CWinReader::Release()
{
	unsigned int v1;
	unsigned int cRef;

	v1 = this->m_cRef - 1;
	this->m_cRef = v1;
	cRef = v1;
	if ( !v1 && this )
		delete this;
	return cRef;
}

HRESULT CWinReader::SetInput( XUINT32 cBuffer, XUINT8 *pBuffer )
{
	HGLOBAL hGlob; 
	void *pvGlob; 
	HRESULT hr; 

	hGlob = GlobalAlloc(2u, cBuffer);
	pvGlob = GlobalLock(hGlob);
	if ( pvGlob )
	{
		memcpy(pvGlob, pBuffer, cBuffer);

		if ( this->m_pStream )
		{
			this->m_pStream->Release();
			this->m_pStream = NULL;
		}

		if ( SUCCEEDED(hr = CreateStreamOnHGlobal(hGlob, TRUE, &this->m_pStream)))
		{
			ULARGE_INTEGER streamSize;
			streamSize.QuadPart = cBuffer;
			if ( SUCCEEDED(hr = this->m_pStream->SetSize(streamSize)))
			{
				if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &this->m_pReader, NULL)))
				{
					return hr;
				}

				if (FAILED(hr = this->m_pReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit)))
				{
					return hr;
				}

				hr = this->m_pReader->SetInput((IUnknown *)this->m_pStream);
			}
		}
	}
	else
	{
		hr = 0x8007000Eu;
	}
	return hr;
}

HRESULT CWinReader::Read( PALNodeType *pType )
{
	return this->m_pReader->Read((XmlNodeType *)(int *)pType);
}

HRESULT CWinReader::GetPrefix( XUINT32 *pcString, XCHAR * *ppString )
{
	return this->m_pReader->GetPrefix((LPCWSTR *)ppString,pcString);
}

HRESULT CWinReader::GetNamespaceUri( XUINT32 *pcString, XCHAR * *ppString )
{
	return this->m_pReader->GetNamespaceUri((LPCWSTR *)ppString,pcString);
}

HRESULT CWinReader::GetLocalName( XUINT32 *pcString, XCHAR * *ppString )
{
	return this->m_pReader->GetLocalName((LPCWSTR *)ppString,pcString);
}

HRESULT CWinReader::GetValue( XUINT32 *pcString, XCHAR * *ppString )
{
	return this->m_pReader->GetValue((LPCWSTR *)ppString,pcString);
}

BOOL CWinReader::EmptyElement()
{
	return this->m_pReader->IsEmptyElement();
}

HRESULT CWinReader::FirstAttribute()
{
	return this->m_pReader->MoveToFirstAttribute();
}

HRESULT CWinReader::NextAttribute()
{
	return this->m_pReader->MoveToNextAttribute();
}

HRESULT CWinReader::GetPosition( XUINT32 *pnLine, XUINT32 *pnColumn )
{
	HRESULT hr = S_OK;
	XASSERT_SUCCESSED(this->m_pReader->GetLineNumber(pnLine));
	XASSERT_SUCCESSED(this->m_pReader->GetLinePosition(pnColumn));
	return hr;
}
